"use client";

import React, { useState, useEffect } from 'react';
import ComponentCard from '@/components/common/ComponentCard';
import Button from '@/components/ui/button/Button';
import Badge from '@/components/ui/badge/Badge';

interface TransactionPattern {
  id: string;
  type: 'deposit' | 'withdrawal' | 'defi_interaction' | 'arbitrage' | 'accumulation' | 'distribution' | 'anomaly';
  confidence: number;
  description: string;
  frequency: number;
  avgAmount: number;
  detectedAt: Date;
}

interface BehaviorInsight {
  id: string;
  address: string;
  type: 'whale_activity' | 'exchange_flow' | 'defi_farming' | 'cross_chain' | 'suspicious';
  title: string;
  description: string;
  severity: 'low' | 'medium' | 'high' | 'critical';
  confidence: number;
  timestamp: Date;
}

interface AnomalyAlert {
  id: string;
  address: string;
  type: 'unusual_volume' | 'new_pattern' | 'suspicious_timing' | 'risk_escalation';
  severity: 'low' | 'medium' | 'high' | 'critical';
  title: string;
  description: string;
  detectedAt: Date;
  threshold: number;
  actualValue: number;
}

const PatternMonitoring: React.FC = () => {
  const [patterns, setPatterns] = useState<TransactionPattern[]>([]);
  const [insights, setInsights] = useState<BehaviorInsight[]>([]);
  const [anomalies, setAnomalies] = useState<AnomalyAlert[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeFilter, setActiveFilter] = useState<'all' | 'high_risk' | 'recent'>('all');

  useEffect(() => {
    loadPatternData();
  }, []);

  const loadPatternData = async () => {
    setLoading(true);
    try {
      // Should load actual data from API here
      // Using mock data temporarily
      setTimeout(() => {
        setPatterns([
          {
            id: '1',
            type: 'deposit',
            confidence: 0.85,
            description: 'Frequent deposits to Binance',
            frequency: 15,
            avgAmount: 250000,
            detectedAt: new Date()
          },
          {
            id: '2',
            type: 'defi_interaction',
            confidence: 0.92,
            description: 'Uniswap liquidity mining',
            frequency: 8,
            avgAmount: 500000,
            detectedAt: new Date()
          }
        ]);

        setInsights([
          {
            id: '1',
            address: '0x1234...5678',
            type: 'whale_activity',
            title: 'Whale Address Active',
            description: 'Large holder address has been active recently, may be preparing for major operations',
            severity: 'high',
            confidence: 0.88,
            timestamp: new Date()
          }
        ]);

        setAnomalies([
          {
            id: '1',
            address: '0xabcd...efgh',
            type: 'unusual_volume',
            severity: 'critical',
            title: 'Abnormal Transaction Volume',
            description: 'Transaction volume surged 300% within 24 hours',
            detectedAt: new Date(),
            threshold: 1000000,
            actualValue: 4000000
          }
        ]);

        setLoading(false);
      }, 1000);
    } catch (error) {
      console.error('Failed to load pattern data:', error);
      setLoading(false);
    }
  };

  const getPatternTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      deposit: 'Deposit Pattern',
      withdrawal: 'Withdrawal Pattern',
      defi_interaction: 'DeFi Interaction',
      arbitrage: 'Arbitrage Pattern',
      accumulation: 'Fund Accumulation',
      distribution: 'Fund Distribution',
      anomaly: 'Anomaly Pattern'
    };
    return labels[type] || type;
  };

  const getPatternTypeColor = (type: string): { color: "primary" | "success" | "error" | "warning" | "info" | "light" | "dark"; variant: "light" | "solid" } => {
    const colors: Record<string, { color: "primary" | "success" | "error" | "warning" | "info" | "light" | "dark"; variant: "light" | "solid" }> = {
      deposit: { color: 'warning', variant: 'light' },
      withdrawal: { color: 'info', variant: 'light' },
      defi_interaction: { color: 'success', variant: 'light' },
      arbitrage: { color: 'primary', variant: 'light' },
      accumulation: { color: 'success', variant: 'light' },
      distribution: { color: 'warning', variant: 'light' },
      anomaly: { color: 'error', variant: 'light' }
    };
    return colors[type] || { color: 'light', variant: 'light' };
  };

  const getSeverityColor = (severity: string): { color: "primary" | "success" | "error" | "warning" | "info" | "light" | "dark"; variant: "light" | "solid" } => {
    const colors: Record<string, { color: "primary" | "success" | "error" | "warning" | "info" | "light" | "dark"; variant: "light" | "solid" }> = {
      low: { color: 'success', variant: 'light' },
      medium: { color: 'warning', variant: 'light' },
      high: { color: 'error', variant: 'light' },
      critical: { color: 'error', variant: 'solid' }
    };
    return colors[severity] || { color: 'light', variant: 'light' };
  };

  const filteredInsights = insights.filter(insight => {
    switch (activeFilter) {
      case 'high_risk':
        return insight.severity === 'high' || insight.severity === 'critical';
      case 'recent':
        const now = new Date();
        const hourAgo = new Date(now.getTime() - 60 * 60 * 1000);
        return new Date(insight.timestamp) > hourAgo;
      default:
        return true;
    }
  });

  if (loading) {
    return (
      <div className="p-6">
        <div className="text-center py-12">
          <p className="text-gray-500 dark:text-gray-400">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Page Title */}
      <div>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Pattern Monitoring</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-2">Real-time monitoring of on-chain transaction patterns and anomalous behaviors</p>
      </div>

      {/* Statistics Overview */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <ComponentCard title="Detected Patterns">
          <div className="text-center">
            <p className="text-3xl font-bold text-blue-600">{patterns.length}</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">Active Patterns</p>
          </div>
        </ComponentCard>

        <ComponentCard title="Behavior Insights">
          <div className="text-center">
            <p className="text-3xl font-bold text-green-600">{insights.length}</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">Smart Insights</p>
          </div>
        </ComponentCard>

        <ComponentCard title="Anomaly Alerts">
          <div className="text-center">
            <p className="text-3xl font-bold text-red-600">{anomalies.length}</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">Anomaly Events</p>
          </div>
        </ComponentCard>

        <ComponentCard title="Risk Level">
          <div className="text-center">
            <p className="text-3xl font-bold text-orange-600">Medium</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">Current Risk</p>
          </div>
        </ComponentCard>
      </div>

      {/* 交易模式列表 */}
      <ComponentCard title="活跃交易模式">
        <div className="space-y-4">
          {patterns.map((pattern) => (
            <div key={pattern.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
              <div className="flex justify-between items-start mb-3">
                <div>
                  <div className="flex items-center space-x-2 mb-1">
                    <h4 className="font-semibold text-gray-900 dark:text-white">
                      {getPatternTypeLabel(pattern.type)}
                    </h4>
                    <Badge {...getPatternTypeColor(pattern.type)}>
                      {pattern.type}
                    </Badge>
                  </div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">{pattern.description}</p>
                </div>
                <Badge color="light" variant="light">
                  置信度: {(pattern.confidence * 100).toFixed(1)}%
                </Badge>
              </div>
              
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div>
                  <span className="text-gray-600 dark:text-gray-400">频率:</span>
                  <span className="ml-2 font-medium text-gray-900 dark:text-white">{pattern.frequency}次</span>
                </div>
                <div>
                  <span className="text-gray-600 dark:text-gray-400">平均金额:</span>
                  <span className="ml-2 font-medium text-gray-900 dark:text-white">
                    ${pattern.avgAmount.toLocaleString()}
                  </span>
                </div>
                <div>
                  <span className="text-gray-600 dark:text-gray-400">检测时间:</span>
                  <span className="ml-2 font-medium text-gray-900 dark:text-white">
                    {pattern.detectedAt.toLocaleTimeString()}
                  </span>
                </div>
                <div className="flex justify-end">
                  <Button size="sm" variant="outline">
                    查看详情
                  </Button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </ComponentCard>

      {/* 行为洞察和异常告警 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 行为洞察 */}
        <ComponentCard title="智能洞察">
          <div className="space-y-3">
            <div className="flex space-x-2 mb-4">
              <Button
                size="sm"
                variant={activeFilter === 'all' ? 'solid' : 'outline'}
                onClick={() => setActiveFilter('all')}
              >
                全部
              </Button>
              <Button
                size="sm"
                variant={activeFilter === 'high_risk' ? 'solid' : 'outline'}
                onClick={() => setActiveFilter('high_risk')}
              >
                高风险
              </Button>
              <Button
                size="sm"
                variant={activeFilter === 'recent' ? 'solid' : 'outline'}
                onClick={() => setActiveFilter('recent')}
              >
                最近1小时
              </Button>
            </div>

            {filteredInsights.map((insight) => (
              <div key={insight.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-3">
                <div className="flex justify-between items-start mb-2">
                  <h5 className="font-medium text-gray-900 dark:text-white">{insight.title}</h5>
                  <Badge {...getSeverityColor(insight.severity)}>
                    {insight.severity}
                  </Badge>
                </div>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">{insight.description}</p>
                <div className="flex justify-between items-center text-xs text-gray-500 dark:text-gray-400">
                  <span>地址: {insight.address}</span>
                  <span>置信度: {(insight.confidence * 100).toFixed(1)}%</span>
                </div>
              </div>
            ))}
          </div>
        </ComponentCard>

        {/* 异常告警 */}
        <ComponentCard title="异常告警">
          <div className="space-y-3">
            {anomalies.map((anomaly) => (
              <div key={anomaly.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-3">
                <div className="flex justify-between items-start mb-2">
                  <h5 className="font-medium text-gray-900 dark:text-white">{anomaly.title}</h5>
                  <Badge {...getSeverityColor(anomaly.severity)}>
                    {anomaly.severity}
                  </Badge>
                </div>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">{anomaly.description}</p>
                <div className="grid grid-cols-2 gap-2 text-xs text-gray-500 dark:text-gray-400">
                  <div>
                    <span>阈值: ${anomaly.threshold.toLocaleString()}</span>
                  </div>
                  <div>
                    <span>实际值: ${anomaly.actualValue.toLocaleString()}</span>
                  </div>
                  <div>
                    <span>地址: {anomaly.address}</span>
                  </div>
                  <div>
                    <span>{anomaly.detectedAt.toLocaleTimeString()}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </ComponentCard>
      </div>
    </div>
  );
};

export default PatternMonitoring; 